<template>
  <div>
    <el-row>
      <el-col :span="12">
        <h3>接运量</h3>
      </el-col>
      <el-col :span="12">
        <h3>发运量</h3>
      </el-col>
    </el-row>
    <hr />
    <el-row>
      <el-col :span="12">
        <el-radio-group v-model="radio"
                        class="button">
          <el-radio :label="1">按月</el-radio>
          <el-radio :label="2">按日</el-radio>
        </el-radio-group>
        <div class="plan-box"
             v-show="radio===1">
          <a-month @handleMonth="v=>handleMonthSet(v,'balance')"
                   @handleMonthNum="getMonthNum"
                   :isClickMonth="true"
                   @month="handleCarry"
                   ref="month"
                   @setDate="setBalance"
                   @data="getMonthData"
                   :getData="getMonth"></a-month>
          <el-row class="button">
            <el-col :span="2"
                    class="number">车皮接运</el-col>
            <el-col :span="10">
              <div class="carColor"></div>
            </el-col>
            <el-col :span="2">
              <div>{{ form.carNum }}pcs</div>
              <div>{{ form.carWeight }}t</div>
            </el-col>
          </el-row>
          <el-row class="button">
            <el-col :span="2"
                    class="number">船舶接运</el-col>
            <el-col :span="10">
              <div class="shipColor"></div>
            </el-col>
            <el-col :span="2">
              <div>{{ form.shipNum }}pcs</div>
              <div>{{ form.shipWeight }}t</div>
            </el-col>
          </el-row>
        </div>
        <div class="plan-box"
             v-show="radio===2">
          <a-day ref="day"
                 :getData="getDay"
                 :portCodes="portModelCode"
                 class="to-center"
                 @set-day="v=>loadDataCount(v)"></a-day>
        </div>
      </el-col>
      <el-col :span="12">
        <el-radio-group v-model="radio"
                        class="button">
          <el-radio :label="1">按月</el-radio>
          <el-radio :label="2">按日</el-radio>
        </el-radio-group>
        <div class="plan-box"
             v-show="radio===1">
          <a-month @handleMonth="v=>handleMonthSet(v,'balance')"
                   @handleMonthNum="getMonthNum"
                   :isClickMonth="true"
                   @month="handleCarry"
                   ref="month"
                   @setDate="setBalance"
                   @data="getMonthData"
                   :getData="getMonth"></a-month>
          <el-row class="button">
            <el-col :span="2"
                    class="number">车皮接运</el-col>
            <el-col :span="10">
              <div class="carColor"></div>
            </el-col>
            <el-col :span="2">
              <div>{{ form.carNum }}pcs</div>
              <div>{{ form.carWeight }}t</div>
            </el-col>
          </el-row>
          <el-row class="button">
            <el-col :span="2"
                    class="number">船舶接运</el-col>
            <el-col :span="10">
              <div class="shipColor"></div>
            </el-col>
            <el-col :span="2">
              <div>{{ form.shipNum }}pcs</div>
              <div>{{ form.shipWeight }}t</div>
            </el-col>
          </el-row>
        </div>
        <div class="plan-box"
             v-show="radio===2">
          <a-day ref="day"
                 :getData="getDay"
                 :portCodes="portModelCode"
                 class="to-center"
                 @set-day="v=>loadDataCount(v)"></a-day>
        </div>
      </el-col>

    </el-row>

    <div>
      <el-menu :default-active="activeIndex"
               class="el-menu-demo"
               mode="horizontal"
               @select="handleSelect">
        <el-menu-item index="1">接运</el-menu-item>
        <el-menu-item index="2">发运</el-menu-item>
        <el-menu-item index="3">内转车调度</el-menu-item>

      </el-menu>
      <!-- 接运 -->
      <div v-show="show">
        <div class="row"
             @click="handleRouterPush({path:'/goods/enter/arrivalForecastList',name:'到达预报列表'})">
          <svg class="icon svg-icon"
               aria-hidden="true">
            <use xlink:href="#icondaodayubaochakan"></use>
          </svg>到达预报列表
        </div>
        <base-list ref="baselist"
                   :condition="condition"
                   :datas.sync="data"
                   :pageSearch="pageSearch">
          <el-form :inline="true"
                   :model="condition"
                   class="search-form"
                   slot="search"
                   label-width="100px">
            <el-row>
              <el-col :span="8"
                      class="search-width6">
                <el-form-item label="到达预报单号">
                  <el-input v-model="form.name"
                            placeholder=""></el-input>
                  <!-- <auto-search-cargo-type-name @selectName="v=>condition['search_LIKE_cargoTypeName']=v"></auto-search-cargo-type-name> -->
                </el-form-item>
              </el-col>
              <el-col :span="7"
                      class="search-width6">
                <el-form-item label="状态">
                  <el-select v-model="condition['search_EQ_status']"
                             placeholder="请选择"
                             clearable
                             filterable>
                    <el-option v-for="[key, val] in _dictPreStatus"
                               :key="key"
                               :label="val"
                               :value="key"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="7"
                      class="search-width6">
                <el-form-item label="车船号">
                  <el-input type="text"
                            v-model="condition['search_LIKE_barcode']"
                            placeholder="请输入内容"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="7"
                      class="search-width6">
                <el-form-item label="预报来源">
                  <el-select v-model="condition['search_EQ_contractStatus']"
                             placeholder="请选择"
                             clearable
                             filterable>
                    <el-option v-for="[key, val] in _dictContractStatus"
                               :key="key"
                               :label="val"
                               :value="key"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-button type="primary"
                           icon="el-icon-search"
                           class="ml-100"
                           @click="loadData">查 询</el-button>
                <el-button formVisible="true"
                           icon="el-icon-refresh"
                           @click="resuleBtn('aList')">
                  重置
                </el-button>
              </el-col>
            </el-row>
          </el-form>
          <el-table slot="list"
                    :data="data"
                    border
                    stripe
                    show-summary
                    :summary-method="getSummaries"
                    max-height="550">
            <el-table-column type="index"
                             label="序号"
                             width="50"
                             align="center"></el-table-column>
            <el-table-column prop="entrustNo"
                             label="到达预报单号"
                             width="120"></el-table-column>
            <el-table-column prop="status"
                             label="状态"
                             width="100">
              <template slot-scope="scope">
                {{ scope.row.status | _filterPreStatus}}
              </template>
            </el-table-column>
            <el-table-column prop="cargoOwnerName"
                             label="货主"
                             width="150"></el-table-column>
            <el-table-column prop="transhipNo"
                             label="车船号"
                             width="100"></el-table-column>
            <el-table-column prop="forecastNum"
                             label="预计件数"
                             width="100"></el-table-column>
            <el-table-column prop="forecastWeight"
                             label="预计重量（吨）"
                             width="120"></el-table-column>
            <el-table-column prop="transportWay"
                             label="运输方式"
                             width="100">
              <template slot-scope="scope">
                {{ scope.row.transportWay | _filterTransportModeType}}
              </template>
            </el-table-column>
            <el-table-column prop="startOffDate"
                             label="物资发运时间"
                             width="180"></el-table-column>
            <el-table-column prop="forecastArrivalDate"
                             label="预计到达时间"
                             width="180"></el-table-column>
            <el-table-column prop="sourceFrom"
                             label="预报来源"
                             width="100">
              <template slot-scope="scope">
                {{ scope.row.sourceFrom | _filterPresource}}
              </template>
            </el-table-column>
            <el-table-column prop="createBy"
                             label="创建人"
                             width="100"></el-table-column>
            <el-table-column prop="createDateTime"
                             label="创建时间"
                             width="180"></el-table-column>
            <el-table-column label="操作"
                             align="center"
                             width="180"
                             fixed="right">
              <template slot-scope="scope">
                <el-button type="text"
                           size="small"
                           @click="handleViewDialogForm(scope.row)">查看</el-button>
                <el-button type="text"
                           size="small"
                           :disabled="scope.row.status !== 'NOOPERATE'"
                           @click="handleFpRouterPush(scope.row)">分配内转车</el-button>
                <el-button type="text"
                           size="small"
                           :disabled="scope.row.status !== 'NOACCEPT'"
                           @click="confirmForecast(scope.row)">预报确认</el-button>
                <el-button type="text"
                           size="small"
                           :disabled="scope.row.status !== 'NOOPERATE'"
                           @click="consoleForecast(scope.row)">取消确认</el-button>
              </template>
            </el-table-column>
          </el-table>
        </base-list>
      </div>
      <!-- 发运 -->
      <shipment-com v-show="show2"
                    ref="shipmentCom"
                    @load="loadData"></shipment-com>
      <!-- 内转车调度 -->
      <interchange-dispatch-com v-show="show3"
                                ref="interchangeDispatchCom"
                                @load="loadData"></interchange-dispatch-com>
    </div>
    <!-- 预报确认弹框 -->
    <confirm-prediction-form ref="confirmPredictionForm"
                             @load="loadData"></confirm-prediction-form>
    <!-- 查看预报确认弹框 -->
    <view-arrival-forecast-form ref="viewArrivalForecastForm"></view-arrival-forecast-form>
  </div>
</template>

<script>
import {
  getArrivalForecastList,
  getArrivalForecastDetail
} from '@/api/enter/arrivalForecast'
import { cancelForecastConfirm, getCar } from '@/api/accept/carry'
import { getTotalMouth, getTotalDay } from '@/api/accept/accept' //日历
import { getWarehouseList } from '@/api/adminWarehouse/adminWarehouse' //所属仓库来源于仓库设置
import viewArrivalForecastForm from './enter/viewArrivalForecastForm' //查看到达预报
import confirmPredictionForm from './accept/confirmPredictionForm' //预报确认
import shipmentCom from './accept/shipmentCom'
import interchangeDispatchCom from './accept/interchangeDispatchCom'
import autoSearchRoomName from '@/components/autocomplete/autoSearchRoomName'
import autoSearchOrg from '@/components/autocomplete/autoSearchOrg'
import autoSearchName from '@/components/autocomplete/autoSearchName'
import aMonth from '@/components/calendar/a-month'
import aDay from '@/components/calendar/a-day'

function getLastDay(year, month) {
  var new_year = year //取当前的年份
  var new_month = month++ //取下一个月的第一天，方便计算（最后一天不固定）
  if (month > 12) {
    //如果当前大于12月，则年份转到下一年
    new_month -= 12 //月份减
    new_year++ //年份增
  }
  var new_date = new Date(new_year, new_month, 1) //取当年当月中的第一天
  return new Date(new_date.getTime() - 1000 * 60 * 60 * 24).getDate() //获取当月最后一天日期
}

export default {
  name: 'accept',
  components: {
    viewArrivalForecastForm,
    shipmentCom,
    interchangeDispatchCom,
    confirmPredictionForm,
    autoSearchOrg,
    autoSearchName,
    autoSearchRoomName,
    aMonth,
    aDay
  },
  data() {
    return {
      form: this.clearForm(),
      disabled: false,
      condition: {}, // 查询条件
      data: [],
      show: true,
      show2: false,
      show3: false,
      pageSearch: getArrivalForecastList, // 分页查询api接口
      id: null,
      activeIndex: '1',
      planNo: null,
      wrongNum: null,
      radio: 1, //默认选择按月
      portModelCode: '',
      getDay: getTotalDay, //按日
      getMonth: getTotalMouth, //按月
      line: '',
      dialogForm: false,
      form: this.clearForm()
    }
  },
  mounted() {
    // getTotalMouth().then(res => {

    // })
    this.$nextTick(() => {
      this.loadData()
    })
  },
  methods: {
    clearForm() {
      return {
        orgId: '',
        orgId:
          this.$store.state.user.currentUser.org &&
          this.$store.state.user.currentUser.org.id,
        orgName:
          this.$store.state.user.currentUser.org &&
          this.$store.state.user.currentUser.org.name,
        carNum: 0,
        carWeight: 0,
        shipNum: 0,
        shipWeight: 0
      }
    },
    loadData() {
      this.$refs.baselist.loadData()
    },
    loadDataCount(data) {
      this.condition.search_GTE_dateTime = data.date
      this.loadData()
    },
    //获取子组件传递的值
    getMonthData(val) {
      // this.form.carNum = val.carNum
      // this.form.carWeight = val.carWeight
      // this.form.shipNum = val.shipNum
      // this.form.shipWeight = val.shipWeight
    },
    //获取子组件传递的值
    getMonthNum(val) {
      this.form.carNum = val.carNum
      this.form.carWeight = val.carWeight
      this.form.shipNum = val.shipNum
      this.form.shipWeight = val.shipWeight
    },
    handleMonthSet() {},
    handleMonth(item) {
      let data = []
      let title = []
      for (let i = 0; i < item.length; i++) {
        const el = item[i]
        data.push(el.jobNum)
        title.push(el.month)
      }
      this.line = echarts.init(document.getElementById('line'), 'macarons')
      this.line.setOption({
        title: {
          text: '月结金额',
          x: 'center',
          top: 20
        },
        legend: {
          data: ['月结金额'],
          right: 10,
          top: 20,
          orient: 'vertical'
          // y:'center',
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: title
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '月结金额',
            data: data,
            type: 'line',
            smooth: false
          }
        ]
      })
    },
    //接运记录
    handleCarry() {
      this.$nextTick(() => {
        this.handleRouterPush({ path: '/goods/accept/carry', name: '接运记录' })
      })
    },
    setBalance(val) {
      let date = val.split('-')
      let year = date[0]
      let month = date[1]
      let day = date[2]
      let lastDay = getLastDay(year, month)
      sessionStorage.setItem('balanceIndexFirst', val)
      sessionStorage.setItem(
        'balanceIndexLast',
        year + '-' + month + '-' + lastDay
      )
    },
    //切换
    handleSelect(key, keyPath) {
      if (key == 1) {
        this.show = true
        this.show2 = false
        this.show3 = false
      } else if (key == 2) {
        this.show = false
        this.show2 = true
        this.show3 = false
        this.$refs.shipmentCom.loadData()
      } else {
        this.show = false
        this.show2 = false
        this.show3 = true
      }
    },
    //查看
    handleViewDialogForm(item) {
      getArrivalForecastDetail(item.entrustNo).then(res => {
        this.$refs.viewArrivalForecastForm.form = res.data
      })
      this.$refs.viewArrivalForecastForm.dialogForm = true
    },
    //分配内转车
    handleFpRouterPush(row) {
      getCar(row.entrustNo).then(res => {
        sessionStorage.setItem('ITEMS', JSON.stringify(res.data))
      })
      this.$router.push({
        path: '/goods/accept/interchangeDistribution',
        name: '分配内转车'
      })
    },
    //预报确认
    confirmForecast(item) {
      this.$refs.confirmPredictionForm.form = JSON.parse(JSON.stringify(item))
      this.$refs.confirmPredictionForm.form2.sureVos.push({
        arrivePosition: '',
        arriveTime: '',
        detailVos: item.detailVoList,
        inWay: '',
        planNum: 0,
        targetLocation: ''
      })
      this.$refs.confirmPredictionForm.dialogForm = true
    },
    //取消确认
    consoleForecast(item) {
      this.$confirm(`确定要取消到达预报确认吗？?`, '取消确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          cancelForecastConfirm(item.entrustNo).then(res => {
            this.$message({
              type: 'success',
              message: `取消成功!`
            })
            this.loadData()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    //合计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (
          column.property === 'totalReleasedWeight' ||
          column.property === 'totalPledgedWeight' ||
          column.property === 'totalControlWeight' ||
          column.property === 'totalUseWeight'
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index]
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    //返回
    handleRouterPush(val) {
      this.$store.commit('ADD_CACHED_VIEWS', val)
      this.$router.push(val.path)
    }
  }
}
</script>

<style scoped>
.row {
  margin: 20px 0;
  cursor: pointer;
}
.icon {
  margin-bottom: -10px;
  margin-right: 5px;
}
.carColor {
  width: 350px;
  height: 40px;
  background: yellow;
  display: inline-block;
}
.shipColor {
  width: 350px;
  height: 40px;
  background: red;
  display: inline-block;
}
.number {
  line-height: 40px;
}
</style>
